<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\task\Lists;
use app\common\model\task\Userlog;
use think\Db;
use think\Exception;

class Task extends Api
{
    protected $noNeedLogin = "";
    protected $noNeedRight = "*";

    public function lists()
    {
        $model = new Lists();
        $result = $model->user_list($this->auth->id);
        $this->success("", $result);
    }

    public function receive_award()
    {
        $id = $this->request->param("id", 0);
        $task = Lists::where(['id' => $id, 'switch' => 1])->find();
        if (!$task) {
            $this->error("当前任务有误");
        }
        $status = Userlog::check($task, $this->auth->id);
        switch ($status) {
            case -1:
                $this->error("当前任务未完成");
                break;
            case 0:
                Db::startTrans();
                try {
                    Userlog::award($task, $this->auth->id, $this->auth->nickname);//领取奖励
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success("");
                break;
            case 1:
                $this->error("当前任务已完成");
                break;
            default:
                $this->error("当前请求有误");
        }
    }

    //自定义任务
    public function custom()
    {
        $evidence = $this->request->param("evidence");
        if (!$evidence) {
            $this->error("请上传凭证");
        }

        $id = $this->request->param("id", 0);
        $task = Lists::where(['id' => $id])->find();
        if (!$task) {
            $this->error("当前任务有问题");
        } elseif ($task['type'] != 3) {
            $this->error("任务类型有误");
        }
        Userlog::create([
            "user_id" => $this->auth->id,
            "task_id" => $id,
            "status" => 2,
            "is_audit" => 0,
            "evidence" => $evidence
        ]);
        $this->success("");
    }

    public function all_notify()
    {
        $not = new \app\common\model\scroll\Notify();
        $this->success("", $not->field("name,nickname,type")->limit(100)->order("createtime DESC")->select());
    }
}